package com.example.cms.Service.Impl;

import com.example.cms.Dto.UserDto;
import com.example.cms.Service.IUserService;
import com.example.common.Utils.JwtUtil;
import com.example.common.Utils.PageUtil;
import com.example.common.web.exception.CustomerException;
import com.example.common.web.response.ResultCode;
import com.example.user.bean.Config;
import com.example.user.bean.User;
import com.example.user.dao.Extend.UserExtendMapper;
import com.example.user.dao.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/11/1-11-01-16:16
 * @Description：com.example.cms.Service.Impl
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper mapper;
    @Autowired
    private UserExtendMapper extendMapper;

    @Override
    public void deleteById(int id) {
        mapper.deleteByPrimaryKey(id);

    }

    @Override
    public User getUserByName(String name) {

        return extendMapper.selectUserByName(name);
    }

    @Override
    public PageUtil pagesOfUsers(int role, PageUtil pageUtil) {
        //插件 构建limit条件
        PageHelper.startPage(pageUtil.getPageNumber(),pageUtil.getPageSize());
        Map<String,Integer> map = new HashMap<>();
        map.put("role",role);
        //带条件查询 类似于Pageinfo
        Page<User> users = extendMapper.selectConfigs(map);
        pageUtil.setList(users.getResult());
        pageUtil.setTotal(users.getTotal());
        return pageUtil;
    }

    @Override
    public void updateUserById(User user) {
        mapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void updateIconById(Integer id, String icon) {
        extendMapper.updateIconById(id,icon);
    }

    @Override
    public String login(UserDto userDto) {
        //校验用户名密码
        User user = extendMapper.selectUserByName(userDto.getUsername());
        if(user==null || !user.getPassword().equals(userDto.getPassword())){     //用户名不存在或密码错误
            throw new CustomerException(ResultCode.USER_LOGIN_ERROR);
        }
        //账号禁用
        if(user.getStatus()==1){
            throw new CustomerException(ResultCode.USER_ACCOUNT_FORBIDDEN);
        }
        //准备token中的信息

        //通过工具类生成token并返回 简单数据(用户名 头像)
        Map<String, Object> info = new HashMap<>();
        info.put("username",user.getUsername());
        info.put("realname",user.getRealname());

        String token = JwtUtil.sign(user.getUserId()+"",info);
        return token;
    }
}
